package com.sgb.kjwl.view.ui.fragment.manage;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.Gson;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.capital.model.QRcodeEntity;
import com.sgb.capital.view.ui.activity.QrCodeActivity;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentTransportOrderDriverBinding;
import com.sgb.kjwl.di.self.DaggerSelfFragComponent;
import com.sgb.kjwl.di.self.SelfFragModule;
import com.sgb.kjwl.model.entity.transport.order.MyOrderEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.ui.activity.transport.OfflineCollectionConfirmActivity;
import com.sgb.kjwl.view.ui.activity.transport.SureStartTransportActivity;
import com.sgb.kjwl.view.ui.activity.transport.owner.TransportOrderDetailOwnerActivity;
import com.sgb.kjwl.view.ui.adapter.transport.order.TransportOrderDriverAdapter;
import com.sgb.kjwl.viewmodel.manage.AgentTotalOrderModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MToast;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

/**
 *
 * Description:个人中心--代办--货主运输订单
 */
public class AgentTransportOrderDriverFragment extends AppLazyFragment implements TransportOrderDriverAdapter.OrderOnClickListener {
    @Inject
    AgentTotalOrderModel viewModel;

    private FragmentTransportOrderDriverBinding mBinding;
    private TransportOrderDriverAdapter mAdapter;
    private static final int REQUEST_CODE_REFRESH = 4;
    public static final int TO_GOODS_ORDER = 100;//跳转订单详情
    private boolean isLoadMore = false; //是否加载更多
    private MyOrderEntity entity;

    Map mMap;
    private int tabposition = 0;
    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerSelfFragComponent.builder()
                .appComponent(appComponent)
                .selfFragModule(new SelfFragModule())
                .build()
                .inject(this);
    }

    public static AgentTransportOrderDriverFragment newInstance(int position) {
        AgentTransportOrderDriverFragment fragment = new AgentTransportOrderDriverFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(RouterKey.TYPE, position);
        fragment.setArguments(bundle);
        return fragment;
    }

    //个人中心代办订单---物流
    public static AgentTransportOrderDriverFragment newInstance() {
        AgentTransportOrderDriverFragment fragment = new AgentTransportOrderDriverFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_transport_order_driver, container, false);
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mMap = new HashMap();
        tabposition = getArguments().getInt(RouterKey.TYPE);
        mAdapter = new TransportOrderDriverAdapter(getContext(), null);
        viewModel.getTransList(getContext(), false,0);
        mAdapter.SetOrderListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mBinding.recyclerView.setLayoutManager(layoutManager);
        mBinding.recyclerView.setLoadingMoreEnabled(true);
        mBinding.recyclerView.setAdapter(mAdapter);
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                isLoadMore = false;
                viewModel.getTransList(getContext(), isLoadMore,0);

            }

            @Override
            public void onLoadMore() {
                isLoadMore = true;
                viewModel.getTransList(getContext(), isLoadMore,0);
            }
        });

        mAdapter.setOnItemClick(new AdapterOnItemClick<MyOrderEntity>() {
            @Override
            public void onItemClick(MyOrderEntity MyOrderEntity, int position) {
                ActivityJump.jumpToActivity(getContext(), TransportOrderDetailOwnerActivity.class, Pair.create("no", MyOrderEntity.getOrderNo()),
                        Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.CAR_OWNER));
            }
        });
        viewModel.getTransOrderEntity().observe(getViewLifecycleOwner(), new Observer<MyOrderEntity>() {
            @Override
            public void onChanged(MyOrderEntity myOrderEntity) {
                if (myOrderEntity != null){
                    sureOrderSuccess(myOrderEntity);
                }
            }
        });
        viewModel.getTransOrderList().observe(getViewLifecycleOwner(), new Observer<List<MyOrderEntity>>() {
            @Override
            public void onChanged(List<MyOrderEntity> leaseOrderListEntities) {
                if (leaseOrderListEntities.size()==0&&isLoadMore==false){
                    mBinding.recyclerView.refreshComplete();
                    mAdapter.setDatas(null);
                    mBinding.recyclerView.setVisibility(View.GONE);
                    mBinding.emptyView.setVisibility(View.VISIBLE);
                    mBinding.recyclerView.setLoadingMoreEnabled(true);
                    mAdapter.notifyDataSetChanged();
                }else {
                    mBinding.recyclerView.setVisibility(View.VISIBLE); showList(leaseOrderListEntities, isLoadMore);
                }

            }
        });
    }

    @Override
    protected void onLazyLoad() {
        isLoadMore = false;
        viewModel.getTransList(getContext(), false,0);
    }


    /**
     * 显示数据
     *
     * @param list       数据
     * @param isLoadMore 是否加载更多
     */
    public void showList(List<MyOrderEntity> list, boolean isLoadMore) {
        mBinding.recyclerView.refreshComplete();
        if (isLoadMore) {
            if (null != list && list.size() > 0) {
                mBinding.recyclerView.loadMoreComplete();
                mAdapter.addDatas(list);
            } else {
                mBinding.recyclerView.setNoMore(true);
            }
            mBinding.recyclerView.setVisibility(View.VISIBLE);
        } else {
            mBinding.recyclerView.refreshComplete();
            if (null != list && list.size() > 0) {
                //mBinding.recyclerView.setVisibility(View.VISIBLE);
                mBinding.emptyView.setVisibility(View.GONE);
                mAdapter.setDatas(list);
                mBinding.recyclerView.setLoadingMoreEnabled(true);
                mAdapter.notifyDataSetChanged();
            } else {
                mAdapter.setDatas(null);
                //mBinding.recyclerView.setVisibility(View.GONE);
                mBinding.emptyView.setVisibility(View.VISIBLE);
                mBinding.recyclerView.setLoadingMoreEnabled(true);
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void btnGoClick(String s, MyOrderEntity item) {
        this.entity = item;
        switch (s) {
            case "确认发车":
                //TODO 去确认发车界面
                if (!TextUtils.isEmpty(item.getMessagePrice()) && !NumberUtil.trim0(item.getMessagePrice()).equals("0")) {
                    SureStartTransportActivity.start(getContext(), item.getOrderNo(), SureStartTransportActivity.START_TRANSPORT_UN_INFOPRICE, item.getMessagePrice());
                } else {
                    SureStartTransportActivity.start(getContext(), item.getOrderNo(), SureStartTransportActivity.START_TRANSPORT);
                }
                break;
            case "收款二维码":
                setGoCapitalCenter(item);
                break;
            case "确认送达":
                SureStartTransportActivity.start(getActivity(), item.getOrderNo(), SureStartTransportActivity.ARRIVED, item.getAllFreight());
                break;
        }
    }

    @Override
    public void btnOffline(MyOrderEntity entity) {
        if (entity != null && !TextUtils.isEmpty(entity.getOrderNo()) && !TextUtils.isEmpty(entity.getAllFreight()))
            OfflineCollectionConfirmActivity.start(getActivity(), entity.getOrderNo(), entity.getAllFreight());
    }
    private void setGoCapitalCenter(MyOrderEntity item) {
        viewModel.getPayFreight(getActivity(), item.getOrderNo());
        viewModel.ldTradeNo.observe(getActivity(), info -> {
            if ("".equals(info.getFreightOrderNo())) {
                return;
            }
            QRcodeEntity qRcodeEntity = new QRcodeEntity();
            qRcodeEntity.amount = info.getAmount() + "";
            qRcodeEntity.orderId = info.getFreightOrderNo();
            qRcodeEntity.payType = "WX";
            String json = new Gson().toJson(qRcodeEntity);
            QrCodeActivity.start(getActivity(), json);

        });
    }
    public void refreshData() {
        isLoadMore = false;
        viewModel.getTransList(getContext(), isLoadMore,0);
    }
    /**
     * 确认订单成功
     */
    public void sureOrderSuccess(MyOrderEntity item) {
        MToast.showToast(getContext(), "操作成功");
        refreshData();
        ActivityJump.jumpToActivity(getContext(), TransportOrderDetailOwnerActivity.class, Pair.create("no", item.getOrderNo()),
                Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.CAR_OWNER));
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReFresh(ZMessageEvent event) {
        if (event.code == Constants.EVENT_REFRESH) {
            refreshData();
        }

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LogisticsEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_SURE_START_TRANSPORT_SUCCESS) {
            refreshData();
        }else
        if (event.getMessageTag() == Constants.EVENT_REFRESH_ORDER) {
            refreshData();
        }else if (event.getMessageTag() == EventConstant.EVENT_ORDER_DETAIL_REFRESH){
            refreshData();
        }
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
